#!/bin/sh
################################################################################
# lirc
#
# This script configures and starts LIRC.
################################################################################
. /etc/rc.d/functions

# Find USB devices associated with each LIRC device and disable ACPI wakeup.
rc_wakeup_disable() {
    local device_list="$1"

    local devpath
    local lirc_list
    local lirc
    local name
    local busnum
    local serial
    local entry
    local device
    local status

    if [ ! -r "/sys/class/lirc" ] ; then
        /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: no /sys/class/lirc"
        return
    fi
    lirc_list=`cd /sys/class/lirc ; ls -1`

    for lirc in ${lirc_list} ; do

        if [ -z "${lirc}" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: empty device..."
            continue
        fi

        name=`/usr/bin/udevadm info --query=name --root --path=/sys/class/lirc/${lirc}`
        /bin/echo " ${device_list}" | grep -q " ${name},"
        if [ $? -ne 0 ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: no devicelist from ${lirc}"
            continue
        fi

        devpath=`/usr/bin/readlink -f "/sys/class/lirc/${lirc}/device"`
        devpath=`/usr/bin/dirname "${devpath}"`
        devpath=`/usr/bin/dirname "${devpath}"`
        devpath=`/usr/bin/dirname "${devpath}"`

        if [ ! -r "${devpath}/busnum" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: no busnum in ${devpath}"
            continue
        fi

        busnum=`/bin/cat "${devpath}/busnum" 2> /dev/null`
        if [ $? -ne 0 ] || [ -z "${busnum}" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: no busnum from ${devpath}"
            continue
        fi

        if [ ! -r "${devpath}/subsystem/devices/usb${busnum}/serial" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: no serial in ${devpath}/subsystem/devices/usb${busnum}"
            continue
        fi

        serial=`/bin/cat "${devpath}/subsystem/devices/usb${busnum}/serial"`
        if [ $? -ne 0 ] || [ -z "${serial}" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: can't find serial in ${devpath}/subsystem/devices/usb${busnum}/serial"
            continue
        fi

        if [ ! -r "/proc/acpi/wakeup" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: can't read from /proc/acpi/wakeup..."
            continue
        fi

        entry=`/bin/cat /proc/acpi/wakeup | /bin/grep -e "${serial}\$" | /bin/sed -e 's%  *% %g'`
        if [ $? -ne 0 ] || [ -z "${entry}" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: can't find ${serial} in /proc/acpi/wakeup..."
            continue
        fi

        device=`/bin/echo ${entry} | /usr/bin/cut -d ' ' -f 1`
        if [ $? -ne 0 ] || [ -z "${device}" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: can't find device in ${entry}"
            continue
        fi

        status=`/bin/echo ${entry} | /usr/bin/cut -d ' ' -f 3`
        if [ $? -ne 0 ] || [ -z "${status}" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: can't detarmine status in ${entry}"
            continue
        fi

        if [ ! -w "/proc/acpi/wakeup" ] ; then
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] ERROR disabling S3 wake-up: can't write to /proc/acpi/wakeup..."
            continue
        fi

        if [ "${status}" = "*enabled" ] ; then
            /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Per request disabling S3 wake-up on ${device}..."
            /bin/echo ${device} > /proc/acpi/wakeup
            if [ $? -ne 0 ] ; then
                continue
            fi
        else
            /usr/bin/logger -t minimyth -p "local0.err" "[init.d/lirc] Per request disabling S3 wake-up on ${device}...but it is already disabled!"
        fi
    done
}

start() {

    /bin/touch /var/lib/init/lirc.inprogress

    /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lirc] Starting..."

    # Create directories used by the LIRC daemon.
    /bin/mkdir -p /var/lock
    /bin/mkdir -p /var/run/lirc

    if [ "x${MM_LIRC_USE_DEVINPUT}" = "xyes" ] ; then

        # Starting LIRC in devinput mode
        /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lirc] Starting in devinput mode..."

        /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lirc] Starting eventlircd..."
        /usr/sbin/eventlircd -v --evmap=/etc/eventlircd.d --socket=/var/run/lirc/lircd --release=:UP &
        /bin/ln -s /var/run/lirc/lircd /dev/lircd

    else

        # Starting LIRC in traditional way
        /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lirc] Starting in lirc daemon mode..."
        /bin/ln -s /var/run/lirc/lircd-lirc0 /var/run/lirc/lircd
        /bin/ln -s /var/run/lirc/lircd-lirc0 /dev/lircd

    fi

    # Auto-configure usage of 'irexec'.
    if [ "x${MM_LIRC_IREXEC_ENABLED}" = "xauto" ] ; then

        /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Attempting to auto-configure usage of irexec"

        MM_LIRC_IREXEC_ENABLED='no'

        if [ -e /etc/lirc/lircrc ] ; then

            # Only one level of includes is supported.
            lircrc_files="/etc/lirc/lircrc `/bin/cat /etc/lirc/lircrc | /bin/grep -e '^include ' | /bin/sed -e 's%^include *%%'`"

            for lircrc_file in ${lircrc_files} ; do

                if /bin/cat ${lircrc_file} | /bin/grep -q -e '^ *prog *= *irexec' ; then
                    MM_LIRC_IREXEC_ENABLED='yes'
                fi

           done

        fi
    fi

    # Start the irexec daemon.
    if [ "x${MM_LIRC_IREXEC_ENABLED}" = "xyes" ] ; then

        /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Starting irexec daemon..."
        /usr/bin/irexec -d /etc/lirc/lircrc

    fi

    # Starting irsend daemon
    if [ "x${MM_EXTERNAL_AMPLI_POWER_ENABLED}" = "xyes" ] || \
       [ "x${MM_EXTERNAL_TV_POWER_ENABLED}"    = "xyes" ] || \
       [ "x${MM_EXTERNAL_VOLUME_ENABLED}"      = "xyes" ] ; then

        /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Starting irsend daemon..."
        /usr/bin/irsend_daemon &

    fi

    # Disable wakeup on remote.
    if [ "x${MM_LIRC_WAKEUP_ENABLED}" = "xno" ] ; then
        rc_wakeup_disable "${MM_LIRC_DEVICE_LIST}"
    fi

    # Making default jumppoints
    main_menu_jumppoint=`mm_mythdb_jumppoints_get 'Main Menu'`

    if [ "x${main_menu_jumppoint}" = "xAlt+h" ] ; then

        /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Not initial run - settings seems to be already defaulted..."

    else

        /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Initial run - will defaulting some settings..."

        mm_mythdb_jumppoints_update 'Main Menu' 'Alt+h'

        if [ "x${MM_LIRC_FETCH_LIRCRC}" = "xno" ] ; then

            /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Initial run with build-in lircrc file - will defaulting major MythTV jumppoints..."

            mm_mythdb_jumppoints_update 'Program Guide'          'Alt+e'
            mm_mythdb_jumppoints_update 'Program Finder'         'Alt+f'
            mm_mythdb_jumppoints_update 'TV Recording Playback'  'Alt+r'
            mm_mythdb_jumppoints_update 'Live TV'                'Alt+t'
            mm_mythdb_jumppoints_update 'Status Screen'          'Alt+i'
            mm_mythdb_jumppoints_update 'MythGallery'            'Alt+p'
            mm_mythdb_jumppoints_update 'MythGame'               'Alt+g'
            mm_mythdb_jumppoints_update 'Play music'             'Alt+m'
            mm_mythdb_jumppoints_update 'MythNews'               'Alt+n'
            mm_mythdb_jumppoints_update 'Video Default'          'Alt+v'
            mm_mythdb_jumppoints_update 'Play radio stream'      'Alt+s'
            mm_mythdb_jumppoints_update 'MythWeather'            'Alt+w'
            mm_mythdb_jumppoints_update 'ZoneMinder Events'      'Alt+z'
            mm_mythdb_jumppoints_update 'MythNetSearch'          'Alt+a'
            mm_mythdb_jumppoints_update 'Standby Mode'           'Alt+b'
        fi

    fi

    # Making default keybindings
    /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Defaulting critical MythTV keybindings..."
    mm_mythdb_keybindings_update "Main Menu"                   "EXIT"           "Ctrl+Esc"
    mm_mythdb_keybindings_update "Main Menu"                   "EXITPROMPT"     ""

    /usr/bin/logger -t minimyth -p "local0.info" "[init.d/lirc] Defaulting critical MythTV user settings..."
    mm_mythdb_settings_set       'NetworkControlEnabled'       '1'
    mm_mythdb_settings_set       'OverrideExitMenu'            '6'
    mm_mythdb_settings_set       'HaltCommand'                 'poweroff'
    mm_mythdb_settings_set       'RebootCommand'               'reboot'
    mm_mythdb_settings_set       'HideMouseCursor'             '1'

    /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lirc] Started with return code=0..."

    /bin/rm -f /var/lib/init/lirc.inprogress

    return 0
}

stop() {
    mm_message_output info "stopping remote control ..."

    if [ -n "`/bin/pidof irexec`" ] ; then
        /usr/bin/killall irexec
    fi
    if [ -n "`/bin/pidof irxevent`" ] ; then
        /usr/bin/killall irxevent
    fi
    if [ -n "`/bin/pidof eventlircd`" ] ; then
        /usr/bin/killall eventlircd
    fi
    if [ -n "`/bin/pidof irsend_daemon`" ] ; then
        /usr/bin/killall irsend_daemon
    fi
}

case $1 in
    start) start ;;
    stop)  stop  ;;
esac

exit 0
